package com.example.order.utility;

import com.alibaba.fastjson2.JSONObject;
import com.example.common.response.BizException;
import com.example.common.util.encryption.Encryption;
import lombok.extern.slf4j.Slf4j;

import java.security.NoSuchAlgorithmException;

@Slf4j
public class EncryptOrderId {
    public static boolean isValidOrderId(String orderId) {
        JSONObject jsonOrderId = JSONObject.parseObject(orderId);
        if(jsonOrderId == null){
            log.warn("IsValidOrderIdReq rpc 订单号格式错误");
            throw new BizException(100, "订单号格式错误");
        }
        if(! jsonOrderId.containsKey("orderId") || ! jsonOrderId.containsKey("token")){
            log.warn("IsValidOrderIdReq rpc 订单号格式错误");
            throw new BizException(100, "订单号格式错误");
        }

        try {
            if(Encryption.md5(jsonOrderId.get("orderId").toString()).equals(jsonOrderId.getString("token"))){
                return true;
            }
            return false;
        } catch (NoSuchAlgorithmException e) {
            return false;
        }
    }

    public static String encryptOrderId(Long orderId) {
        JSONObject jsonOrderId = new JSONObject();
        jsonOrderId.put("orderId", orderId);
        try {
            jsonOrderId.put("token", Encryption.md5(orderId.toString()));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return jsonOrderId.toString();
    }

    public static Long decryptOrderId(String orderId) {
        if(! isValidOrderId(orderId)){
            log.warn("IsValidOrderIdReq rpc 订单号格式错误");
            throw new BizException(100, "订单号格式错误");
        }
        JSONObject jsonOrderId = JSONObject.parseObject(orderId);
        return jsonOrderId.getLong("orderId");
    }
}
